<template>
  <div class="match_list">
    <el-row align="middle" class="pt-5">
      <el-col :span="16">
        <p class="main_title">指定赛</p>
      </el-col>
    </el-row>

    <div style="display: flex; margin: 15px;0;15px;0">
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-row :gutter="20" class="search_block pt-5">
          <el-col :span="2" class="hori-cond"><label class="form-label">状态</label></el-col>
          <el-col :span="3">
            <el-select class="formItem" v-model="searchData.jobstatus" placeholder="全部" @change="doList" clearable
              filterable>
              <el-option v-for="item in jobstatuses" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2" class="hori-cond"><label class="form-label">直播源</label></el-col>
          <el-col :span="3">
            <el-select class="formItem" v-model="searchData.web" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in webs" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="9">
            <el-input class="formItem" v-model="searchData.term" placeholder="请输入编号\直播源\URL" @change="doList" clearable>
              <el-button slot="append" icon="el-icon-search" @click="doList">查询</el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>
      <div style="flex: 0 0 23%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <div style="float:right">
          <label class="form-label">代理剩余时间：{{stateNum}}秒&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <el-button size="medium" type="primary" @click="addMatch">新增<i
              class="el-icon-circle-plus-outline"></i></el-button>
          <el-button size="medium" type="primary" @click="readToken">设置<i
              class="el-icon-circle-plus-outline"></i></el-button>
        </div>
      </div>
    </div>

    <div style="position: sticky">
      <div class="table_container">
        <el-table v-loading="loading" :data="matches" :header-cell-style="boxheader" :row-style="{height:0+'px'}"
          :cell-style="{padding:0+'px'}" style="width: 100%">
          <el-table-column prop="id" label="序号" min-width="60px"></el-table-column>
          <el-table-column min-width="80px" prop="web" label="直播源" show-overflow-tooltip>
            <!-- <template slot-scope="scope">
              <span class="btnCell">{{ scope.row.url }}</span>
            </template> -->
          </el-table-column>
          <el-table-column min-width="420px" align="left" label="直播链接" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="btnCell" @click="openUrl(scope.row.url)">{{ scope.row.url }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="60px" align="left" label="状态" :render-header="renderheader" prop="status">
            <template slot-scope="scope">
              <span
                :style="{color: scope.row.jobstatus === 0 ? '#ed5b56' : scope.row.jobstatus === 1 ? '#4190f7' : scope.row.jobstatus === 2 ? '#72c140' : '#606266'}">
                <span v-if="scope.row.jobstatus === 0" class="priority_notbegin">{{ $t("status.NOTBEGIN") }}</span>
                <span v-if="scope.row.jobstatus === 1" class="priority_middle">{{ $t("status.RUNNING") }}</span>
                <span v-if="scope.row.jobstatus === 2" class="priority_finished">{{ $t("status.FINISHED") }}</span>
                <el-tooltip placement="right" effect="light">
                  <div slot="content" class="joberror">
                    {{ scope.row.joberror }}
                  </div>
                  <span v-if="scope.row.jobstatus === 3" class="priority_exception" @click="showExp(scope.row.joberror)"
                    style="cursor: pointer">{{ $t("status.EXCEPTION") }}</span>
                </el-tooltip>
                <span v-if="scope.row.jobstatus === 4" class="priority_expired">{{ $t("status.EXPIRED") }}</span>
                <span v-if="scope.row.jobstatus === 5" class="priority_report">{{ $t("status.REPORT") }}</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="85px" align="center" label="抓取时间" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>
                {{(scope.row.jobtime||' ').split(" ")[0] }}
                <br />
                {{(scope.row.jobtime||' ').split(" ")[1] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="70px" prop="amount" label="羽数" show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="50px" prop="raceid" label="基础清单" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>
                {{ scope.row.raceid ? '有' : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="50px" prop="checkid" label="集鸽清单" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>
                {{ scope.row.checkid ? '有' : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="60px" align="center" label="下载" :render-header="renderheader">
            <template slot-scope="scope">
              <span class="download">
                <span class="btnCell" @click="downLoad('xls', scope.row)">成绩单</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" align="center" :label="$t('common.OPER')" fixed="right">
            <template slot-scope="scope">
              <el-button style="margin-left: 0px !important" type="text" @click="grabMatch(scope.row)">抓取</el-button>
              <el-button
                v-if="(scope.row.web === 'dps' || scope.row.web === 'qingge' || scope.row.web === 'dps2') && scope.row.jobstatus == 1"
                style="margin-left: 0px !important" type="text" @click="stopMatch(scope.row)">取消</el-button>
              <el-button v-if="(scope.row.web === 'dps' || scope.row.web === 'qingge' || scope.row.web === 'dps2')"
                style="margin-left: 0px !important" type="text" @click="bindMatch(scope.row)">绑定</el-button>
              <el-button v-if="(scope.row.web === 'dps2')" style="margin-left: 0px !important" type="text"
                @click="checkMatch(scope.row)">上传</el-button>
              <el-button style="margin-left: 0px !important" type="text" @click="removeMatch(scope.row)">删除</el-button>
              <el-button v-if="scope.row.web === 'dps2'" style="margin-left: 0px !important" type="text"
                @click="verifyMatch(scope.row)">校对</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table_page">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchData.curpage" :page-sizes="[5, 10, 20, 50]" :page-size="searchData.pagesize"
            layout="total, sizes,  pager, jumper" :total="searchData.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 异常详情弹框 -->
    <el-dialog title="错误详情" :visible.sync="expVisible" :width="width" append-to-body>
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <textarea rows="20" nz-input v-model="expDetail" style="width: 100% !important"></textarea>
    </el-dialog>

    <el-dialog title="新增指定赛" :visible.sync="addVisible" :width="width" :close-on-click-modal="false">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <add-match :detailData="detailData" v-if="addVisible" @closeVisible="closeVisible"></add-match>
    </el-dialog>

    <el-dialog title="绑定基础清单" :visible.sync="listVisible" :width="width" append-to-body>
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-upload class="upload-demo" ref="uploadRef" action="/" :http-request="uploadFile" accept=".xlsx"
          :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess">
          <el-button size="small" type="primary">点击上传基础清单（xlsx格式）进行绑定</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div> -->
        </el-upload>
      </div>
    </el-dialog>

    <el-dialog title="上传集鸽清单" :visible.sync="checkVisible" :width="width" append-to-body>
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-upload class="upload-demo" ref="upload2Ref" action="/" :http-request="upload2File" accept=".xls"
          :show-file-list="false" :before-upload="handleBeforeUpload2" :on-success="handleUpload2Success">
          <el-button size="small" type="primary">点击上传集鸽清单（xls格式）</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div> -->
        </el-upload>
      </div>
    </el-dialog>

    <el-dialog title="设置身份信息" :visible.sync="tokenVisible" :width="width" append-to-body>
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <label class="">F12->选择网络->sign接口->Headers->找到token</label>
      <p></p>
      <textarea rows="8" nz-input v-model="tokenData" style="width: 100% !important"></textarea>
      <div style="float:right">
        <el-button style="" size="small" type="primary" @click="saveToken">保存</el-button>
      </div>
      <p></p>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/index";
import { hideLoading, showLoading } from "@/utils/loading";

import enlargeImg from "@/assets/images/icon_2.png";
import narrowImg from "@/assets/images/icon_3.png";
import matchService from "@/service/matchService";
import receiptService from "@/service/receiptService";
import i18n from "@/lang";

import AddMatch from "./components/AddMatch.vue";
const baseURL = process.env.BASE_API;

export default {
  name: "MatchList",
  components: {
    AddMatch,
  },
  data() {
    return {
      loading: false,
      jobstatuses: [
        { key: "", value: i18n.t("status.ALL") },
        { key: 0, value: i18n.t("status.NOTBEGIN") },
        { key: 1, value: i18n.t("status.RUNNING") },
        { key: 2, value: i18n.t("status.FINISHED") },
        { key: 3, value: i18n.t("status.EXCEPTION") },
        { key: 4, value: i18n.t("status.EXPIRED") },
        // {key: 5, value: i18n.t('status.REPORT')}
      ],
      webs: [
        { key: "", value: i18n.t("status.ALL") },
        { key: "dps", value: "dps" },
        { key: "xingela", value: "xingela（云南红河）" },
        { key: "sgr", value: "sgr（赛格锐）" },
        { key: "qingge", value: "qingge（青鸽网）" },
        { key: "dps2", value: "dps2" },
        { key: "gxb", value: "gxb（鸽小宝）" },
      ],
      boxheader: {
        // background: '#eef1f6',
        color: "#606266",
        fontWeight: 800,
        borderBottom: "2px solid #EBEEF5",
      },
      searchData: {
        curpage: 1,
        pagesize: 10,
        total: 0,
      },
      matches: [],
      width: "600px",
      expVisible: false, // 异常详情弹框
      expDetail: "", // 异常内容
      addVisible: false, // 新增抓取任务弹框
      detailData: "",
      listVisible: false,
      bindData: {},
      checkVisible: false,
      checkData: {},
      tokenVisible: false,
      tokenData: "",
      iconImg: enlargeImg,
      stateNum: 100,
    };
  },
  watch: {},
  mounted: function () {
    // console.log(window.screen.height);
    this.$store.dispatch("setActive", "13").then(() => {
      // this.$root.eventBus.$emit('exit')
    });
  },
  created() {
    this.ELHeight = window.screen.height - 320;
    if (window.screen.height === 900) {
      this.ELHeight = 460;
    }
    this.doTimer();
    this.doList();
  },
  destroyed() {},
  methods: {
    parseTime,
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1]),
      ]);
    },
    // 展示异常弹框
    showExp(data) {
      this.expVisible = true;
      this.expDetail = data;
    },
    doTimer() {
      receiptService.remainder({}).then((res) => {
        if (res.status === 200 && res.data.result === 0) {
          this.stateNum = res.data.data;
          this.showTimer();
        }
      });
    },
    showTimer() {
      let timer = setInterval(() => {
        this.stateNum--;
        if (this.stateNum === 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    doList() {
      this.listMatch();
    },
    listMatch() {
      this.loading = true;
      let searchData = { ...this.searchData };
      delete searchData.total;
      let params = searchData;
      matchService.listMatch(params).then((res) => {
        this.loading = false;
        if (res.status === 200 && res.data.result === 0) {
          this.matches = res.data.data;
          this.searchData.total = res.data.total;
        }
      });
    },
    addMatch() {
      let vdata = {};
      vdata.webs = this.webs.slice(1);
      this.detailData = JSON.stringify(vdata);
      // console.log(this.detailData)
      this.addVisible = true;
    },
    readToken() {
      matchService.readToken({}).then((res) => {
        if (res && res.data.result === 0) {
          this.tokenData = res.data.data;
        }
        this.tokenVisible = true;
      });
    },
    saveToken() {
      matchService.saveToken({ token: this.tokenData }).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("保存成功!");
        } else {
          this.$message.error("保存失败！");
        }
        this.tokenVisible = false;
      });
    },
    grabMatch(row) {
      this.grab(row);
    },
    async grab(row) {
      // showLoading('.list_setting')
      let params = { id: row.id };
      await matchService.grabMatch(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("抓取成功!");
        } else {
          this.$message.error("抓取失败！");
        }
        // hideLoading()
        this.listMatch();
      });
    },
    stopMatch(row) {
      matchService.stopMatch({ id: row.id }).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("取消成功!");
          this.listMatch();
        } else {
          this.$message.error("抓取失败！");
        }
      });
    },
    bindMatch(row) {
      this.bindData.id = row.id;
      this.listVisible = true;
    },
    checkMatch(row) {
      this.checkData.id = row.id;
      this.checkVisible = true;
    },
    removeMatch(row) {
      this.$confirm("确认删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = { id: row.id };
          matchService.deleteMatch(params).then((res) => {
            if (res && res.data.result === 0) {
              this.$message.success("删除成功!");
            } else {
              this.$message.error("删除失败！");
            }
            this.listMatch();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleBeforeUpload(file) {
      // console.log('file', file);
      const suffix = file.name.split(".").pop().toLowerCase();
      if (!["xlsx"].includes(suffix)) {
        return this.$message.error(`请上传xlsx文件.`);
      }
    },
    uploadFile(param) {
      // console.log('param-----' + param.file);
      const formData = new FormData();
      formData.append("id", this.bindData.id);
      formData.append("file", param.file);
      matchService.bindDove(formData).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("绑定成功!");
          this.listVisible = false;
          this.listMatch();
        } else {
          this.$message.error("绑定失败！");
        }
      });
    },
    handleUploadSuccess(res) {
      // console.log("res", res);
    },
    handleBeforeUpload2(file) {
      // console.log('file', file);
      const suffix = file.name.split(".").pop().toLowerCase();
      if (!["xls"].includes(suffix)) {
        return this.$message.error(`请上传xls文件.`);
      }
    },
    upload2File(param) {
      // console.log("param-----" + param.file);
      const formData = new FormData();
      formData.append("id", this.checkData.id);
      formData.append("file", param.file);
      matchService.checkDove(formData).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("上传成功!");
          this.checkVisible = false;
          this.listMatch();
        } else {
          this.$message.error("上传失败！");
        }
      });
    },
    handleUpload2Success(res) {
      // console.log("res", res);
    },
    verifyMatch(row) {
      // this.goto('VerifyList', row.id)
      this.$router.push("/verify-list?id=" + row.id);
    },
    // 打开公告链接
    openUrl(url) {
      window.open(url, "_blank");
    },
    // 下载原始数据
    downLoad(type, row) {
      if (row.jobstatus != 2) {
        this.$message.info("请等待成绩下载完成...");
        return;
      }
      if (type === "xls") {
        this.$message.info("正在成绩单...");
        window.open(baseURL + "/match/download/xls?id=" + row.id, "_self");
      }
    },
    handleSizeChange(val) {
      this.searchData.pagesize = val;
      this.listMatch();
    },
    handleCurrentChange(val) {
      this.searchData.curpage = val;
      this.listMatch();
    },
    enlarge() {
      if (this.width === "600px") {
        this.width = "1000px";
        this.iconImg = narrowImg;
      } else {
        this.width = "600px";
        this.iconImg = enlargeImg;
      }
    },
    closeVisible(type) {
      this.addVisible = false;
      this.detailVisible = false;
      if (type !== "cancel") {
        this.doList(type);
      }
    },
    goto(type, id) {
      this.$router.push({
        name: `${type}`,
        params: { id: id },
      });
    },
  },
};
</script>

<style>
.match_list .list_setting {
  padding: 24px;
  margin-top: 14px;
  box-sizing: border-box;
  background: #fff;
  min-height: calc(100vh - 130px);
}
.main_title {
  color: #343434;
  font-size: 18px;
  margin: 7px 0 0 0;
}

.area-detail {
  margin-top: 0px;
}

.define_label {
  line-height: 25px;
  text-align: left;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 340px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.define_span {
  line-height: 25px;
  text-align: right;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 480px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-back {
  width: 90%;
  /*height: 209px;*/
  background: rgba(233, 233, 233, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.message-task {
  width: 90%;
  /*height: 209px;*/
  background: rgba(203, 225, 203, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.joberror {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item {
  margin-top: 10px;
  padding-top: 5px;
  margin-right: 15px;
}
.match_list .sponsorCell {
  vertical-align: middle;
}
.match_list .sponsorLink {
  margin-left: 3px;

  text-decoration: none;
  color: #1890ff;
}
.btnCell {
  color: #1890ff;
  cursor: pointer;
}
.download .btnCell {
  border-right: 1px solid #eee;
  padding: 0px 5px;
  display: inline-block;
}
.download .btnCell:nth-last-child(1) {
  border-right: 0px;
  padding-right: 0px;
}
.table_page {
  background: #fff !important;
  padding: 10px;
  text-align: right;
}
.receiptDetailDialog .el-dialog__body {
  padding: 10px 20px 30px !important;
}
.formItem {
  width: 100%;
}
.red {
  color: #f56c6c;
}
</style>
